import gzip
import logging
import multiprocessing
import os
import shlex
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory

Logger = logging.getLogger("MATCH")
FORMAT = "%(asctime)s %(message)s"
logging.basicConfig(format=FORMAT)
Logger.setLevel(logging.DEBUG)
import toml


def config_to_map(filename):
    return toml.load(filename)


def download_clash_kernel(url, dst):
    filename = os.path.basename(url)
    if not os.path.exists(dst):
        os.makedirs(dst, exist_ok=True)
    out_file = os.path.join(dst, filename)
    cmd = f"wget -c {url} -P {out_file}"
    Logger.debug(cmd)
    p = subprocess.Popen(shlex.split(cmd),
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    Logger.debug(f"out = {out.decode('utf-8')}")

    # with TemporaryDirectory() as p:
    #     cmd = f"wget -c {url} -P {p}"
    #     Logger.debug(cmd)
    #     out, err = subprocess.Popen(shlex.split(cmd),
    #                                 stdout=subprocess.PIPE,
    #                                 stderr=subprocess.PIPE).communicate()
    #     Logger.debug(f"out = {out.decode('utf-8')}")


if __name__ == "__main__":
    config_file = Path(__file__).parent.joinpath("config.toml")
    config = config_to_map(config_file)
    clash_kernel_url = config["clash"]["url"]
    save_path = config["clash"]["save_path"]
    download_clash_kernel(clash_kernel_url, save_path)
